#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include "Fail.hpp"

class UdpClient
{
public:
    //默认构造
    UdpClient(std::string ip, uint16_t port)
        : _ip(ip)
        , _port(port)
    {}

    //初始化
    void InitClient()
    {
        //创建套接字
        _sock = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sock < 0)
        {
            perror("create socket fail");
            exit(SOCKET_FAIL);
        }
    }

    //发消息
    void Send()
    {   
        //服务器方--收信息方
        struct sockaddr_in receiver;
        memset(&receiver, 0, sizeof(receiver));
        receiver.sin_family = AF_INET;
        receiver.sin_port = htons(_port);
        receiver.sin_addr.s_addr = inet_addr(_ip.c_str());
        
        while(true)
        { 
            std::string message;
            std::cerr << "place enter# ";
            getline(std::cin, message);

            if(sendto(_sock, message.c_str(), message.size(), 0, (struct sockaddr*)&receiver, sizeof(receiver)) < 0)
            {
                perror("sendto fail");
                exit(SENDTO_FAIL);
            }
        }
    }

    //返回套接字
    int& GetSock()
    {
        return _sock;
    }

    ~UdpClient()
    {}

private:
    int _sock; //套接字
    std::string _ip;
    uint16_t _port; //端口
};
